package com.gitee.swsk33.demoserviceorder.service.impl;

import com.gitee.swsk33.demoentity.dataobject.Order;
import com.gitee.swsk33.demoentity.dataobject.User;
import com.gitee.swsk33.demoentity.model.Result;
import com.gitee.swsk33.demoserviceorder.dao.OrderDAO;
import com.gitee.swsk33.demoserviceorder.feignclient.UserClient;
import com.gitee.swsk33.demoserviceorder.service.OrderService;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.gitee.swsk33.demoentity.dataobject.table.OrderTableDef.ORDER;

@Component
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDAO orderDAO;

	@Autowired
	private UserClient userClient;

	@Override
	public Result<Order> getById(int id) {
		Order getOrder = orderDAO.selectOneById(id);
		if (getOrder == null) {
			return Result.resultFailed("找不到订单！");
		}
		// 根据userId字段，通过Feign客户端远程调用用户模块得到该订单关联的用户对象
		Result<User> getUser = userClient.getById(getOrder.getUserId());
		if (!getUser.isSuccess()) {
			return Result.resultFailed("查找订单关联的用户信息失败！");
		}
		// 查找成功后手动进行组装
		getOrder.setUser(getUser.getData());
		return Result.resultSuccess("查找订单成功！", getOrder);
	}

	@Override
	public Result<List<Order>> getByUserId(int userId) {
		// 先通过远程调用获取对应用户
		Result<User> getUser = userClient.getById(userId);
		if (!getUser.isSuccess()) {
			return Result.resultFailed("查找订单关联的用户信息失败！");
		}
		// 然后查找相关订单
		QueryWrapper condition = new QueryWrapper();
		condition.where(ORDER.USER_ID.eq(userId));
		List<Order> orders = orderDAO.selectListByQuery(condition);
		// 手动组装
		orders.forEach(each -> {
			each.setUser(getUser.getData());
		});
		return Result.resultSuccess("查询成功！", orders);
	}

}